package com.thread;

import java.util.concurrent.Semaphore;
import java.util.function.IntConsumer;

public class Solution1195 {
}

//https://leetcode.cn/problems/fizz-buzz-multithreaded/solutions/40343/javashi-xian-shi-yong-semaphore-huo-zhe-reentrantl/
class FizzBuzz {
    private int n;
    Semaphore sf, sb, sfb, sn;

    public FizzBuzz(int n) {
        this.n = n;
        sf = new Semaphore(0);
        sb = new Semaphore(0);
        sfb = new Semaphore(0);
        sn = new Semaphore(1);
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for (int i = 3; i <= n; i += 3) {
            if (i % 5 != 0) {
                sf.acquire();
                printFizz.run();
                sn.release();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for (int i = 5; i <= n; i += 5) {
            if (i % 3 != 0) {
                sb.acquire();
                printBuzz.run();
                sn.release();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for (int i = 15; i <= n; i += 15) {
            sfb.acquire();
            printFizzBuzz.run();
            sn.release();
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            sn.acquire();
            if (i % 3 == 0 && i % 5 != 0) {
                sf.release();
            } else if (i % 3 != 0 && i % 5 == 0) {
                sb.release();
            } else if (i % 3 == 0 && i % 5 == 0) {
                sfb.release();
            } else {
                printNumber.accept(i);
                sn.release();
            }
        }
    }
}